package org.alex.samples.web;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.alex.samples.model.User;
import org.alex.samples.service.IUserService;
import org.alex.samples.vo.CommonMessageResultVO;
import org.alex.samples.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import util.ExcelUtils;

@Controller
public class UserController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private LocaleResolver localeResolver;
	
	@RequestMapping(value = "/changeLocale")
	public String changeLocale(HttpServletRequest rq,HttpServletResponse rep,String localeType){
		if("en_US".equals(localeType)){
			localeResolver.setLocale(rq, rep, Locale.US);
		}else if("zh_CN".equals(localeType)){
			localeResolver.setLocale(rq, rep, Locale.CHINA);
		}
		return "redirect:/users";
	}
	
	
	@RequestMapping("/users")
	public String users(Model model) throws Exception{
		List<UserVO> list2 = userService.findAllUsers();
		model.addAttribute("userList", list2);
		return "user/userList";
	}
	@RequestMapping(value = "/toEditUser", method = RequestMethod.POST)
	@ResponseBody
	public UserVO toeditUser(Integer userId) throws Exception{
		User user = userService.getUserById(userId);
		UserVO uservo = new UserVO();
		if(user != null){
			try {
				uservo.setAddress(user.getAddress());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				uservo.setBirthday(sdf.format(user.getBirthday()));
				uservo.setEmail(user.getEmail());
				uservo.setGender(user.getGender());
				uservo.setId(user.getId());
				uservo.setName(user.getName());
				uservo.setPassword(user.getPassword());
				uservo.setTel(user.getTel());
			} catch (Exception e) {
				throw new Exception("没有找到该用户");
			}
		}
		return uservo;
	}
	
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public CommonMessageResultVO saveUser(@Valid UserVO userVO,BindingResult bindingResult) throws Exception{
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		resultVO.setSuccess(false);
		try{
		User user = new User();
		user.setAddress(userVO.getAddress());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		user.setBirthday(sdf.parse(userVO.getBirthday()));
		user.setEmail(userVO.getEmail());
		user.setGender(userVO.getGender());
		Calendar now = Calendar.getInstance();
		user.setLast_lock_time(now.getTime());
		user.setLogin_fail_count(0);
		user.setName(userVO.getName());
		user.setPassword(userVO.getPassword());
		user.setTel(userVO.getTel());
		userService.createUser(user);
		resultVO.setSuccess(true);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return resultVO;
	}
	
	@RequestMapping(value = "/editUser",method = RequestMethod.POST)
	@ResponseBody
	public CommonMessageResultVO editUser(@Valid UserVO userVO,BindingResult bindingResult)throws Exception{
		CommonMessageResultVO resultvo = new CommonMessageResultVO();
		resultvo.setSuccess(false);
		User user = userService.getUserById(userVO.getId());
		if(user != null){
			user.setAddress(userVO.getAddress());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			user.setBirthday(sdf.parse(userVO.getBirthday()));
			user.setGender(userVO.getGender());
			user.setName(userVO.getName());
			user.setPassword(userVO.getPassword());
			user.setTel(userVO.getTel());
			userService.editUser(user);
			resultvo.setSuccess(true);
		}
		return resultvo;
	}
	
	
	@RequestMapping(value = "/delete/{id}",method= RequestMethod.GET)
	public String toEdit(RedirectAttributes redirectAttributes,@PathVariable Integer id) throws Exception{
		userService.deleleUser(id);
		redirectAttributes.addFlashAttribute("message", "删除成功");
		return "redirect:/users";
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/uploadFile")
	public CommonMessageResultVO uploadFile(@RequestParam(value = "uploadFile")MultipartFile[] uploadFile,HttpSession session,Model model){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		MultipartFile uploadSimpleFile = uploadFile[0];
		String fileName = uploadSimpleFile.getOriginalFilename();
		
		//获取文件后缀名
		String postfix = fileName.substring(fileName.lastIndexOf("."));
		try{
			if(ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix) || ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix)){
				userService.saveStudentByExcel(uploadSimpleFile.getInputStream(),postfix);
				resultVO.setSuccess(true);
			}else{
				resultVO.setMessage("文件格式不正确。");
			}
		}catch (Exception e) {
			e.printStackTrace();
			resultVO.setMessage("批量导入失败。");
		}
		return resultVO;
		
	}
}
